package org.ns.summer.beans.definition;

import org.ns.summer.beans.error.BeansException;
import org.ns.summer.core.BeanUtils;

import java.util.ArrayList;
import java.util.List;

public class DefaultBeanDefinition implements BeanDefinition {
    private String beanClassName;
    private Class<?> beanClass;
    private ClassLoader classLoader = getClass().getClassLoader();
    private List<PropertyDefinition> propertyDefinitions = new ArrayList<>();
    @Override
    public String getBeanClassName() {
        return beanClassName;
    }


    public void setBeanClassName(String beanClassName) {
        this.beanClassName = beanClassName;
    }
    @Override
    public ClassLoader getClassLoader() {
        return classLoader;
    }

    public void setClassLoader(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }

    @Override
    public Class<?> getBeanClass() {
        if (beanClass == null) {
            try {
                beanClass = BeanUtils.createClass(beanClassName, classLoader);
            } catch (ClassNotFoundException e) {
                throw new BeansException(beanClassName, e);
            }
        }
        return beanClass;
    }

    @Override
    public List<PropertyDefinition> getPropertyDefinitions() {
        return propertyDefinitions;
    }

    public void setBeanClass(Class<?> beanClass) {
        this.beanClass = beanClass;
    }

    public void addPropertyValue(String name, Object value) {
        DefaultPropertyDefinition defaultPropertyDefinition = new DefaultPropertyDefinition();
        defaultPropertyDefinition.setPropertyName(name);
        defaultPropertyDefinition.setPropertyValue(value);
        propertyDefinitions.add(defaultPropertyDefinition);
    }

    public void addPropertyRef(String name, String ref) {
        DefaultPropertyDefinition defaultPropertyDefinition = new DefaultPropertyDefinition();
        defaultPropertyDefinition.setPropertyName(name);
        defaultPropertyDefinition.setPropertyRef(ref);
        propertyDefinitions.add(defaultPropertyDefinition);
    }

}
